package ms.demo003;

import java.util.HashSet;


public class Client {
    public static void main(String[] args) {
        HashSet<Person> set = new HashSet<>();
        Person p1 = new Person("张三", 18);
        set.add(p1);
        Person p2 = new Person("张三", 18);
        set.add(p2);
        /** 如果没有重写 Person#hashCode()方法，HashSet中还是能将姓名和年龄相同的人员对象添加进集合，
         * 达不到认定姓名和年龄相同就认为是同一个人，不准存入Set集合的目的。
         */
        // 所以必须重写了equals()方法后必须要重写hashCode()方法。
        System.out.println(p1.equals(p2));

        System.out.println(p1.hashCode());
        System.out.println(p2.hashCode());

        set.forEach(x->{
            System.out.println(x);
        });
    }
}

class Person {

    private String name;
    private Integer age;

    public Person(){

    }

    public Person(String name){
        this.name = name;
    }

    public Person(String name, Integer age){
        this.name = name;
        this.age= age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return name.equals(person.name) && age.equals(person.age);
    }

//    @Override
//    public int hashCode() {
//        return Objects.hash(name, age);
//    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
